//
//  YHTimer.swift
//  YHKit
//
//  Created by amovision on 2025/8/5.
//

import Foundation

public class YHTimer {
  private var timer: DispatchSourceTimer?
  public private(set) var isRunning: Bool = false
  private let lock = DispatchSemaphore(value: 1)
  public var isRepeats: Bool {
    repeatCount == 0
  }

  public var repeatCount: Int = 1
  public var interval: TimeInterval
  public var fireTime: TimeInterval
  public var counter: Int = 1
  public var timerHandler: ((_ counter: Int, _ isFinished: Bool) -> Void)?

  public init(fireTime: TimeInterval = 0, interval: TimeInterval = 1, repeatCount: Int = 1, timerHandler: ((_ counter: Int, _ isFinished: Bool) -> Void)? = nil) {
    self.fireTime = fireTime
    self.interval = interval
    self.repeatCount = repeatCount
    self.timerHandler = timerHandler
  }

  public func resetCounter() {
    counter = 1
  }
  
  public func fire() {
    invalidate()
    lock.wait()
    defer { lock.signal() }
    guard !isRunning else { return }
    NSLog("YHTimer fire")
    isRunning = true
    timer = DispatchSource.makeTimerSource(queue: DispatchQueue.main)
    timer?.schedule(deadline: .now() + fireTime, repeating: interval)
    timer?.setEventHandler { [weak self] in
      guard let self else { return }
      timerHandler?(counter, counter == repeatCount)
      if counter == repeatCount {
        invalidate()
        return
      }
      counter += 1
    }
    timer?.resume()
  }

  public func invalidate() {
    lock.wait()
    defer { lock.signal() }
    if isRunning {
      NSLog("YHTimer invalidate")
      counter = 1
      timer?.cancel()
      timer = nil
      isRunning = false
    }
  }

  deinit {
    invalidate()
    NSLog("YHTimer deinit")
  }
}
